revision:
Syntax:
HTMLElementObject.className : returns the className property: the class, or a space-separated list of classes, of an element.
HTMLElementObject.className = class : sets the className property.
property value:
class : the class name(s) of an element; separate multiple classes with spaces, like "test demo".
example
I am DIV
Click the button to set a class for DIV:
click "toggle" (many times) to toggle between two classes.
<div>
<div id="DIV">
<p> I am DIV</p>
</div>
<p style="font-size: 0.9vw;">Click the button to set a class for DIV:</p>
<button onclick="firstFunction()">set class</button>
<p style="font-size: 0.9vw;">click "toggle" (many times) to toggle between two classes.</p>
<button onclick="secondFunction()">toggle</button>
</div>
<style>
.myStyle1{background-color: coral; padding: 0.5vw;}
.newStyle{background-color: lightblue; text-align: center; padding: 1vw;}
</style>
<script>
function firstFunction() {
document.getElementById("DIV").className = "myStyle1";
}
function secondFunction() {
const element = document.getElementById("DIV");
if (element.className == "myStyle1") {
element.className = "newStyle";
} else {
element.className = "myStyle1";
}
}
</script>
The class attribute of "DIV2" is:
<div>
<div id="DIV2" class="style_1 test example">
I am a DIV element with multiple classes
</div>
<p>The class attribute of "DIV2" is:</p>
<p id="prop"></p>
</div>
<style>
.style_1 {background-color: coral; padding: 16px;}
.test {text-align: center; }
.example {font-size: 25px;}
</style>
<script>
let value = document.getElementById("DIV2").className;
document.getElementById("prop").innerHTML = value;
</script>
</pre>